Shader "MyTest/SDF_HealthBar"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _Value ("Health", Range(0,1)) = 0.5
        _Width ("Width", Range(0,1)) = 0.8
        _BorderSize ("BorderSize", Range(0,0.5)) = 0.1
        _BorderColor ("BorderColor", Color) = (1,1,1,1)
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;
            float _Value;
            float _Width;
            float _BorderSize;
            fixed4 _BorderColor;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                //SDF
                float2 coord = i.uv;
                coord.x *= 8;
                float2 pointOnCenterLine = float2(clamp(i.uv.x, 1 - _Width, _Width) * 8, 0.5);
                float sdf = distance(coord, pointOnCenterLine) * 2 - 1;
                clip(-sdf);

                //SDF Border
                float sdf_Border = sdf + _BorderSize;
                float borderMask = step(0, sdf_Border);
                //smooth border
                //float pd = fwidth(sdf_Border);
                //borderMask = saturate(sdf_Border / pd);

                //Health Bar
                float value = step(i.uv.x, _Value);
                fixed4 col = tex2D(_MainTex, float2(_Value,i.uv.y));
                col.xyz *= value;

                col = (1 - borderMask) * col  + borderMask * _BorderColor;
                return col;
            }
            ENDCG
        }
    }
}
